package com.hp.bon.sgw.wh.processor;

import static com.hp.bon.sgw.Constants.LOG;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.stream.XMLInputFactory;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.bean.SysParamBean;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.ChannelServer;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.processor.Processor;
import com.hp.bon.sgw.core.route.RouteInfo;
import com.hp.bon.sgw.domain.Node;
import com.hp.bon.sgw.service.ConfigService;
import com.hp.bon.sgw.wh.bean.NetListQueryPara;
import com.hp.bon.sgw.wh.bean.Recharge;
import com.hp.bon.sgw.wh.channel.handler.DetailQueryHandle;
import com.hp.bon.sgw.wh.channel.handler.RechargeHandle;

public class DetailQueryProcessor extends Processor {
	static XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	@Autowired
	private ConfigService configService;
	
	@Override
	public int process(CallParam callParam) {
		XmlMessage reqM = (XmlMessage) callParam.getRequest();
		XmlMessage ackM = new XmlMessage(false);
		ackM.setRC("0");
		ackM.setDS("");
		ackM.setSIG("");
		Map<String,Object> map = new HashMap<String, Object>();
		String reqXML = "";
		try {
			map = convertReq(reqM);
		} catch (Exception e) {
			LOG.warn("Invalid request DATA format ,not valid xml: ", e);
			ackM.setRC(String.valueOf(Constants.ResultCode.UNKNOW_TAG));
			ackM.setDS("Invalid request DATA format ,not valid xml: " + e.toString());
		}
		
		Element serviceInformation = DocumentHelper.createElement("Service_Information");
		
		Element element = serviceInformation.addElement("ValueType");
		element.setText("1");
		element = serviceInformation.addElement("Value");
		element.setText(map.get("CustMobile").toString());
		element = serviceInformation.addElement("Area_Code");
		element.setText("	");
		element = serviceInformation.addElement("QueryType");
		element.setText("1");
		
		XmlMessage req = new XmlMessage(true);
		req.setMsgTime(System.currentTimeMillis());
			req.setSCID("QueryServ.HSS@027.ctnbc-bon.net");
			req.setSIG(null);
			req.setREPTAG(0);
			req.setDATA(serviceInformation.asXML());
			req.setDataElement(serviceInformation);
		
		DetailQueryHandle detailQueryHandle = new DetailQueryHandle(map,configService);
		CallParam callParam1 = new CallParam(req.getMID(), req.getSCID(),req, req.getUID(), detailQueryHandle);
		BuzProcessorManager.getInstance().processRequest(callParam1);
		
		
//		Node node = ChannelServer.routeMap.get(callParam.getServiceContextId()).curNode;
//		callParam.setToNode(node);
//		String url = callParam.getToNode().getServerUrl();
//		PostMethod post = new PostMethod(url);
//		boolean sendOK = false;
//		String resp = "";
//		
//		try {
//			RequestEntity requestEntity = new StringRequestEntity(reqXML, "text/xml", "UTF-8");
//			post.setRequestEntity(requestEntity);
//			HttpClient client = new HttpClient();
//			int timeout = configService.getIntValue(SysParamBean.KEY_AGREEMENT_SCSP_MSG_Timeout, 60);
//			client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout*1000);
//			client.executeMethod(post);
//			resp = post.getResponseBodyAsString();
//			sendOK = true;
//		} catch (UnsupportedEncodingException e) {
//			LOG.warn("unsupported encoding of request.", e);
//			ackM.setRC(String.valueOf(Constants.ResultCode.TYPE_ERROR));
//			ackM.setDS("unsupported encoding of request.");
//		} catch (HttpException e) {
//			LOG.warn("send ws request to BON error.", e);
//			ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
//			ackM.setDS("send ws request to BON error.");
//		} catch (IOException e) {
//			LOG.warn("send ws request to BON time out: ", e);
//			ackM.setRC(String.valueOf(Constants.ResultCode.BON_TIMEOUT));
//			ackM.setDS("send ws request to BON time out: ");
//		} catch (Exception e){
//			LOG.warn("send ws request to BON error.", e);
//			ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
//			ackM.setDS("send ws request to BON error.");
//		}
//		
//		//解析返回串
//		String data = "";
//		if(sendOK){
//			try {
//				data = parseNetListReturn(resp);
//			} catch (Exception e) {
//				LOG.warn("response from BON is valid.", e);
//				ackM.setRC(String.valueOf(Constants.ResultCode.BON_ERROR));
//				ackM.setDS("response from BON is valid.");
//			}
//		}
//		
//		ackM.setDATA(data);
//		ackM.setMID(reqM.getMID());
//		ackM.setRTT(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(System.currentTimeMillis()));
//		callParam.setResponse(ackM);
//		this.proccessResponse(callParam);
//		
		return 0;
	}


	public int proccessResponse(CallParam callParam) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("OcsSessionCtrlProcessor endProcess");
		}
		callParam.getAsynHandler().onCallResult(callParam);
		return 0;
	}
	
	
	
	private Map<String,Object> convertReq(XmlMessage reqM) throws Exception{
		/*StringBuffer reqXML = new StringBuffer();
		reqXML.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/\'  ");
		reqXML.append("xmlns:ws='http://ws.hquery.ailk.com/'>");
		reqXML.append("<soapenv:Header/>");
		reqXML.append(" <soapenv:Body>");
		reqXML.append("<ws:hquery> <param>");
		reqXML.append("<![CDATA[<query type='1' from='209'><param name='acctId'></param><param name='servid'>19052929130</param><param name='selectType'>1</param><param name='beginDate'>20140412000000</param><param name='endDate'>20140431235959</param><param name='getFlag'>0</param><param name='areaCode'>1001</param><start name='queryBatchStart'></start><start name='queryBatch'></start></query>]]>");
		reqXML.append("	</param></ws:hquery></soapenv:Body></soapenv:Envelope>");*/
		
		Map<String,Object> data= xmlStrToMap(reqM.toString());
		
		return data;
	}
	
	 public static Map<String, Object> xmlStrToMap(String xmlStr) throws Exception {  
	        Map<String, Object> map = new HashMap<String, Object>();  
	        //将xml格式的字符串转换成Document对象  
	        Document doc = DocumentHelper.parseText(xmlStr);  
	        //获取根节点  
	        Element root = doc.getRootElement();  
	        //获取根节点下的所有元素  
	        List children = root.elements();  
	        //循环所有子元素  
	        if(children != null && children.size() > 0) {  
	            for(int i = 0; i < children.size(); i++) {  
	                Element child = (Element)children.get(i);  
	                map.put(child.getName(), child.getTextTrim());  
	                if(child.getName().equals("returnPoint")){
	                	for(int j = 0; j < child.elements().size(); j++) { 
	                		Element child1 = (Element)child.elements().get(j);  
	                		map.put(child1.getName(), child1.getTextTrim());  
	                	}
	                }
	            }  
	        }  
	        return map;  
	    } 

	private String parseNetListReturn(String representation) throws Exception {
		StringBuffer data = new StringBuffer();
		Document doc = DocumentHelper.parseText(representation);
		Element root = doc.getRootElement();
		Element returnE = root.element("Body").element("hqueryResponse").element("return");
		returnE.setName("Service_Information");
		String xmlStr = returnE.asXML();
    	data.append(xmlStr);
		return data.toString();
	}

	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}

	@Override
	public int endProcess(CallParam arg0) {
		return 0;
	}


	
	
}
